package com.gyl.example.controller;

import com.gyl.common.utils.ExceptionUtil;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import lombok.extern.slf4j.Slf4j;

/**
 * @author gyl
 * @date 2022/5/12 - 16:05
 */
@ServerEndpoint("/websocket/{username}")
@Component
@Slf4j
public class WebSocketController {
    public static Map<String,Session> sessionMap = new HashMap<>();
    /**
     * 连接建立的时候
     * @param session
     * @param userName
     * @throws IOException
     */
    @OnOpen
    public void openConnetion(Session session, @PathParam("username")String userName) throws IOException {
        sessionMap.put(userName,session);
        log.info("检测到客户端{}上线了",userName);
        session.getBasicRemote().sendText(userName + "上线了");
    }

    /**
     * 接收消息的时候
     * @param session
     */
    @OnMessage
    public void message(Session session,String message,@PathParam("username") String userName){
        log.info("检测到客户端{}发来消息了：{}",userName,message);
        // 发送给其他的session信息
        sessionMap.forEach((k,v)->{
            if(!k.equals(userName)){
                try {
                    v.getBasicRemote().sendText("【"+ userName + "】:" + message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 客户端关闭
     * @param session
     */
    @OnClose
    public void close(Session session,@PathParam("username") String userName){
        log.info("客户{}下线了",userName);
        sessionMap.remove(userName);
    }

    @OnError
    public void error(Session session,Throwable throwable){
        log.info("检测到session{}出现错误了",session.getId());
        log.error(ExceptionUtil.printStackTrace((Exception) throwable));
    }


}
